package com.yunxin.utils.db;

import lombok.Data;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class DBConnection {


    private Connection connection;

    public List<Map> select(String sql, Object... args) throws SQLException {
        PreparedStatement selectStmt = connection.prepareStatement(sql);
        for(int i=0;i<args.length;i++){
            selectStmt.setObject(i+1,args[i]);
        }
        ResultSet resultSet = selectStmt.executeQuery(sql);
        /**
         * 获取列名
         */
        ResultSetMetaData rsmd = resultSet.getMetaData();
        int count=rsmd.getColumnCount();
        String[] cols=new String[count];
        for(int i=0;i<count;i++){
            cols[i]=rsmd.getColumnName(i+1);
        }
        /**
         * 读取数据
         */
        List<Map> list = new ArrayList<>();
        while (resultSet.next()){
            Map map = new HashMap();
            for(String col: cols){
                map.put(col,resultSet.getObject(col));
            }
            list.add(map);
        }
        return list;
    }

    public synchronized void simpleUpdate(String sql, Object... args) throws SQLException{
        PreparedStatement selectStmt = null;
        try{
            connection.setAutoCommit(false);
            selectStmt = connection.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                selectStmt.setObject(i+1,args[i]);
            }
            selectStmt.executeUpdate(sql);
            connection.commit();
        }catch (Throwable t){
            connection.rollback();
        }
    }

    public synchronized int update(String sql, Object... args) throws SQLException{
        PreparedStatement selectStmt = null;
            selectStmt = connection.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                selectStmt.setObject(i+1,args[i]);
            }
            return selectStmt.executeUpdate(sql);
    }

    public synchronized void setAutoCommit(boolean autoCommit) throws SQLException {
        connection.setAutoCommit(autoCommit);
    }

    public synchronized void rollback() throws SQLException {
        connection.rollback();
    }

    public synchronized void commit() throws SQLException {
        connection.commit();
    }

    public void close() throws SQLException {
        if(connection!=null){
            connection.close();
        }
    }




}
